package com.gitee.wsl.mathematics.geometry.d2.contour.segment.ext

import com.gitee.wsl.mathematics.geometry.d2.base.YPolarity
import com.gitee.wsl.mathematics.geometry.d2.contour.segment.Segment2D
import com.gitee.wsl.mathematics.vector.ext.times


fun Segment2D.offset(
    distance: Double,
    stepSize: Double = 0.01,
    yPolarity: YPolarity = YPolarity.CW_NEGATIVE_Y
): List<Segment2D> {
    return if (linear) {
        val n = normal(0.0f, yPolarity)
        if (distance > 0.0) {
            listOf(Segment2D(start + distance * n, end + distance * n))
        } else {
            val d = direction()
            val s = distance.coerceAtMost(length / 2.0)
            val candidate = Segment2D(
                start - s * d + distance * n,
                end + s * d + distance * n
            )
            if (candidate.length > 0.0) {
                listOf(candidate)
            } else {
                emptyList()
            }
        }
    } else {
        reduced(stepSize).map { (it as Segment2D).scale(distance, yPolarity) }
    }
}
